use std::collections::HashMap;
use mio::tcp::TcpStream;
use mio::{Poll, PollOpt};
use std::io::Write;

#[derive(Debug)]
struct RequestPackage{
    // version:u8,
    modtype:u8,
    subtyoe:u8,
    ctaskid:u8,
    datalen:u8,
    msg:Vec<u8>
}
#[derive(Debug)]
struct ResposePackage{
    // version:u8,
    modtype:u8,
    subtyoe:u8,
    ctaskid:u8,
    retcode:u8,
    datalen:u8,
    msg:Vec<u8>
}

enum SerivceModType{
    RegisterMod = 1 ,
    UnRegisterMod = 2,
    TranDataMod = 3 ,
}

fn resposeDataPackageToBuffer(resp : &ResposePackage)->Vec<u8> {
    let mut datapackage = vec![];
    // datapackage.push(resp.version);
    datapackage.push(resp.modtype);
    datapackage.push(resp.subtyoe);
    datapackage.push(resp.ctaskid);
    datapackage.push(resp.retcode);
    datapackage.push(resp.datalen);

    for &bitdata in resp.msg.iter() {
        datapackage.push(bitdata);
    }

    datapackage.to_vec()
}

fn proc_depackage(data : &[u8]) ->Option<RequestPackage>
{
    if data.len()>=6 {
        let len:usize = (data[3] + 4 ) as usize;

        if data.len() < len{
            None
        }else {
            let msg = &data[4..len];
            Some(RequestPackage{
                // version: data[0],
                modtype: data[0],
                subtyoe: data[1],
                ctaskid: data[2],
                datalen: data[3],
                msg: msg.to_vec()
            })
        }
    }else {
        None
    }
}

pub fn proc_service(clients_map: &HashMap<usize, TcpStream>, client_id: usize, poll: &Poll, buff: &[u8], len: usize, pollopts: PollOpt, key_map: &HashMap<String, String>)
{
    let depackage = proc_depackage(&buff[0..len]);
    println!("resp : {:?}" , depackage);

    let resposeDataPackage=  match depackage {
        Some(requestPackage)=>{
            // 派发任务

            ResposePackage{
                // version: requestPackage.version,
                modtype: requestPackage.modtype,
                subtyoe:requestPackage.subtyoe,
                ctaskid: requestPackage.ctaskid,
                retcode: 0,
                datalen: 0,
                msg: vec![]
            }
        }   ,
        None=>{
            ResposePackage{
                // version: 1,
                modtype: 0,
                subtyoe: 0,
                ctaskid: 0,
                retcode: 1,
                datalen: 0,
                msg: vec![]
            }
        }
    };

    let resp_vec = resposeDataPackageToBuffer(&resposeDataPackage);

    let mut stream = clients_map.get(&client_id).unwrap();//移除流TCP在stream生命周期结束后主动关闭

    match stream.write(resp_vec.as_ref()) {
        // 发送成功
        Ok(nwrite) => println!("respose ok"),
        Err(e) => println!("write err  {}", e),
    }

}
